// pages/packageA/comment/comment.js
import Dialog from '@vant/weapp/dialog/dialog';
let app = getApp();
const Multipart = require('../../../utils/Multipart.min.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    host: app.globalData.host,
    imgList: [],
    title: "发表评论",
    placeholder: "善语结善缘，恶言伤人心",
    goodsId: "",
    id: "",
    userId: "",
    comment: "",
    cw: 0,
    vh: 0,
  },

  bindKeyInput: function (e) {
    this.setData({
      [e.target.dataset.name]: e.detail.value
    })
  },

  chooseImage() {
    let that = this
    let count = 3 - this.data.imgList.length
    wx.chooseMedia({
      count: count,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      sizeType: ['original', 'compressed'],
      maxDuration: 30,
      camera: 'back',
      success(res) {
        console.log('==== chooseMedia ====', res.tempFiles, res.tempFiles[0].tempFilePath, res.tempFiles[0].size / 1024)
        for (let index = 0; index < res.tempFiles.length; index++) {
          wx.getImageInfo({
            src: res.tempFiles[index].tempFilePath,
            success: (imageInfoRes) => {
              console.log('==== 图片信息 ====', imageInfoRes)
              that.drawImage(res.tempFiles[index].tempFilePath, imageInfoRes, index)
            }
          })
        }
      }
    })
  },

  drawImage(tempFilePath, imageInfoRes, index) {
    let that = this
    const ctx = wx.createCanvasContext('front' + index);
    const canvasWidth = imageInfoRes.width;
    const canvasHeight = imageInfoRes.height;
    const maxWidth = 1024; // 设定最大宽度
    const maxHeight = 1024; // 设定最大高度
    // 计算压缩比例
    const ratio = Math.max(canvasWidth / maxWidth, canvasHeight / maxHeight);
    if (ratio > 1) {
      this.setData({
        cw: canvasWidth / ratio,
        ch: canvasHeight / ratio
      })
      ctx.drawImage(tempFilePath, 0, 0, canvasWidth / ratio, canvasHeight / ratio);
    } else {
      this.setData({
        cw: canvasWidth,
        ch: canvasHeight
      })
      ctx.drawImage(tempFilePath, 0, 0, canvasWidth, canvasHeight);
    }
    // 将canvas画布内的内容导出生成图片
    ctx.draw(true, () => {
      wx.canvasToTempFilePath({
        canvasId: 'front' + index,
        fileType: 'jpg',
        success: (compressRes) => {
          console.log('压缩后的图片路径:', compressRes.tempFilePath);
          // 此时compressRes.tempFilePath即为压缩后的图片路径
          that.setData({
            imgList: this.data.imgList.concat(compressRes.tempFilePath)
          })
        },
        fail: (err) => {
          console.error('导出图片失败:', err);
        }
      });
    });
  },

  delImg(e) {
    let flag = e.currentTarget.dataset.index
    console.log(flag)
    this.setData({
      imgList: this.data.imgList.filter((item, index) => index != flag)
    })
  },

  trendAdd() {
    let that = this
    let param = {
      content: this.data.comment,
      trendsId: this.data.id,
      toUserId: this.data.userId
    }
    wx.post(wx.api.trendAddComment, param, res => {
      console.log('==== trendAdd ====', res)
      Dialog.alert({
        title: '温馨提示',
        message: res.msg,
        confirmButtonText: '好的'
      }).then(() => {
        this.back()
      })
    }, fail => {})
  },

  submit() {
    if (!this.data.comment) {
      return
    }

    if (this.data.id) { // 回复评论
      this.trendAdd()
      return
    }
    wx.showLoading({
      mask: true
    })
    var app = getApp();
    let fields = [{
      name: 'goodsId',
      value: this.data.goodsId
    }, {
      name: 'content',
      value: this.data.comment
    }]
    let files = []
    for (let index = 0; index < this.data.imgList.length; index++) {
      files.push({
        filePath: this.data.imgList[index], //value
        name: 'photos' //key
      })
    }
    console.info(fields, files)
    new Multipart({
      fields, //非文件参数
      files, //文件参数
    }).submit(this.data.host + wx.api.trendAdd, {
      header: {
        "token": app.globalData.token || wx.getStorageSync('token')
      }
    }).then(res => {
      wx.hideLoading()
      if (res.data.code == 200 || res.data.code == 2039 || res.data.code == 2040) {
        console.log('==== add ===', res)
        Dialog.alert({
          title: '温馨提示',
          message: res.data.msg,
          confirmButtonText: '好的'
        }).then(() => {
          this.back()
        })
      } else if (res.data.code == 2002) {
        app.globalData.userInfo = {}
        app.globalData.token = ''
        wx.removeStorage({
          key: 'userInfo'
        })
        wx.removeStorage({
          key: 'token'
        })
        wx.showToast({
          title: '登录过期，请重新登录',
          icon: 'none',
          mask: true,
          duration: 2000
        })
        setTimeout(() => {
          wx.navigateTo({
            url: '/pages/login/login',
          })
        }, 2000)
      } else {
        wx.showModal({
          title: '温馨提示',
          content: res.data.msg,
          showCancel: false
        })
        wx.hideLoading()
      }
    })
  },

  back() {
    wx.navigateBack({
      delta: 1
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.info('==== options ====', options)
    if (options.id) {
      this.setData({
        id: options.id,
        userId: options.userId,
        placeholder: "@ " + options.nickName
      })
    } else {
      this.setData({
        goodsId: options.goodsId
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})